package com.lx.algorithm.Tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

/**
 * Description:
 * 给定一棵二叉树的头节点head，任何两个节点之间都存在距离，
 * 返回整棵二叉树的最大距离
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2021-10-19 11:33:57
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-10-19     张李鑫                     1.0         1.0 Version
 */
public class MaxDistance {

    /**
     * 给定一棵二叉树的头节点head，任何两个节点之间都存在距离，
     * 返回整棵二叉树的最大距离
     */
    public static class Info {
        public int height;
        public int max;

        public Info(int height, int max) {
            this.height = height;
            this.max = max;
        }
    }

    public static int maxDistance(Node node) {
        return process(node).max;
    }

    private static Info process(Node node) {
        if (node == null) {
            return new Info(0, 0);
        }

        Info leftProcess = process(node.left);
        Info rightProcess = process(node.right);

        //先考虑是以当前节点为头节点的情况的最大高度跟最大距离
        int height = Math.max(leftProcess.height, rightProcess.height) + 1;
        int max = Math.max(Math.max(leftProcess.max, rightProcess.max), (leftProcess.height + rightProcess.height + 1));
        return new Info(height, max);
    }


    public static int maxDistance2(Node head) {
        return process1(head).max;
    }

    public static Info process1(Node x) {
        if (x == null) {
            return new Info(0, 0);
        }
        Info leftInfo = process1(x.left);
        Info rightInfo = process1(x.right);
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        int p1 = leftInfo.max;
        int p2 = rightInfo.max;
        int p3 = leftInfo.height + rightInfo.height + 1;
        int maxDistance = Math.max(Math.max(p1, p2), p3);
        return new Info(height, maxDistance);
    }


    public static void main(String[] args) {
        int maxLevel = 4;
        int maxValue = 100;
        int testTimes = 1000000;
        for (int i = 0; i < testTimes; i++) {
            Node head = TreeUtils.generateRandomBST(maxLevel, maxValue);
            if (maxDistance2(head) != maxDistance(head)) {
                System.out.println("Oops!");
            }
        }
        System.out.println("finish!");
    }


}
